package com.kidala.tool;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class URLConnectionTool {

    public static void main(String[] args) {
        URLConnectionTool tool = new URLConnectionTool();
        tool.retrieveSessionID("http://localhost:8080/kidalarichfaces/");
    }

    public String retrieveSessionID(String urlString) {
        String lastId = null;

        for (int z = 0; z < 10; z++) {
            try {
                URL url = new URL(urlString);
                URLConnection urlConnection = url.openConnection();
                if (urlConnection != null) {
                    urlConnection.setRequestProperty("Cookie", lastId);
                    String setCookie = urlConnection
                            .getHeaderField("Set-Cookie");
                    Map<String, List<String>> headerFields = urlConnection
                            .getHeaderFields();
                    System.out.println(headerFields);
                    if (setCookie != null) {
                        lastId = setCookie;
                    }
                    System.out.println(lastId);
                }
                Thread.sleep(1000);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return lastId;
    }

}
